<template>
    <div class="job-plan">
        <el-row class="mb-4">
            <el-col :span="24">
                <!-- 添加任务按钮 -->
                <el-button type="success" @click="openAddDialog">添加任务</el-button>

                <el-button color="#8000ff" @click="handleExecute" :disabled="selectedRows.length !== 1">
                    立刻执行1次
                </el-button>

                <el-button color="#2196F3" @click="openEditDialog(selectedRows[0])"
                    :disabled="selectedRows.length !== 1">
                    编辑
                </el-button>

                <el-button color="#a000a0" @click="handleStart" :disabled="selectedRows.length !== 1">
                    开启任务
                </el-button>

                <el-button color="#F44336" @click="handleStop" :disabled="selectedRows.length !== 1">
                    停止任务
                </el-button>

                <el-button color="#FF3366" @click="handleBatchDelete" :disabled="selectedRows.length === 0"
                    class="ml-2">
                    批量删除
                </el-button>
            </el-col>
        </el-row>

        <!-- 任务列表 -->
        <el-table size="large" border show-overflow-tooltip :data="jobPlans" style="width: 100%"
            @selection-change="handleSelectionChange" ref="table">

            <!-- 复选框列 -->
            <el-table-column type="selection" width="55" />

            <!-- 其他列 -->
            <el-table-column prop="jobName" label="任务名称" />
            <el-table-column prop="jobGroup" label="任务分组" />
            <el-table-column prop="executeNums" label="执行次数" />
            <el-table-column prop="jobCron" label="Cron 表达式" />
            <el-table-column prop="jobClassName" label="任务类名" />
            <el-table-column prop="jobAssemblyName" label="任务程序集名称" />
            <el-table-column prop="jobDescription" label="任务描述" />
            <el-table-column prop="jobParams" label="任务传参" />
            <el-table-column label="启动状态">
                <template #default="{ row }">
                    <!-- 根据 enable 值渲染不同的 tag -->
                    <el-tag :type="row.enable ? 'success' : 'danger'">
                        {{ row.enable ? "已启动" : "未启动" }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="任务开始时间">
                <template #default="{ row }">
                    {{ row.jobBeginTime ? formatDate(row.jobBeginTime) : '' }}
                </template>
            </el-table-column>

            <el-table-column label="任务结束时间">
                <template #default="{ row }">
                    {{ row.jobEndTime ? formatDate(row.jobEndTime) : '' }}
                </template>
            </el-table-column>

            <el-table-column label="操作日志" fixed="right">
                <template #default="scope">
                    <el-popover title="任务执行日志" effect="dark" trigger="hover" width="25%">
                        <template #default>
                            <div v-html="formattedJobRecord(scope.row.jobRecord)"></div>
                        </template>
                        <template #reference>
                            <el-tag>LOG</el-tag>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑任务对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle">
            <el-form :model="currentJob" ref="formRef">
                <el-form-item label="任务名称">
                    <el-input v-model="currentJob.jobName" />
                </el-form-item>
                <el-form-item label="任务分组">
                    <el-input v-model="currentJob.jobGroup" />
                </el-form-item>
                <el-form-item label="Cron 式">
                    <el-input v-model="currentJob.jobCron" />
                </el-form-item>
                <el-form-item label="任务类名">
                    <el-input v-model="currentJob.jobClassName" />
                </el-form-item>
                <el-form-item label="任务程序集名称">
                    <el-input v-model="currentJob.jobAssemblyName" />
                </el-form-item>
                <el-form-item label="任务描述">
                    <el-input v-model="currentJob.jobDescription" />
                </el-form-item>
                <el-form-item label="任务传参">
                    <el-input v-model="currentJob.jobParams" />
                </el-form-item>
                <el-form-item label="启动状态">
                    <el-switch v-model="currentJob.enable" />
                </el-form-item>
                <el-form-item label="任务开始时间">
                    <el-date-picker v-model="currentJob.jobBeginTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                        placeholder="选择时间" />
                    <el-button class="clear" @click="clearStartTime" type="danger">清空</el-button>
                </el-form-item>
                <el-form-item label="任务结束时间">
                    <el-date-picker v-model="currentJob.jobEndTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                        placeholder="选择时间" />
                    <el-button class="clear" @click="clearEndTime" type="danger">清空</el-button>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveJob">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
    QueryJobPlans,
    AddJob,
    ExecuteJob,
    DeleteJobs,
    EditJob,
    StartJob,
    StopJob
} from "../../utils/api";

const formattedJobRecord = (jobRecord) => {
    return jobRecord.replace(/\r\n|\n/g, '<br>');
};

const selectedRows = ref([]);
const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date
        ? date.toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
        })
        : "";
};

// 清空任务开始时间
const clearStartTime = () => {
    currentJob.value.jobBeginTime = null;
};

// 清空任务结束时间
const clearEndTime = () => {
    currentJob.value.jobEndTime = null;
};

const jobPlans = ref([]); // 定时任务列表
const dialogVisible = ref(false); // 控制对话框的显示/隐藏
const dialogTitle = ref("添加任务"); // 对话框标题

const currentJob = ref({
    jobName: "",
    jobGroup: "",
    jobCron: "",
    jobClassName: "",
    jobAssemblyName: "",
    jobDescription: "",
    jobParams: "",
    enable: true,
    jobBeginTime: null,
    jobEndTime: null,
}); // 当前任务对象

// 打开添加任务对话框
const openAddDialog = () => {
    currentJob.value = {
        jobName: "",
        jobGroup: "",
        jobCron: "",
        jobClassName: "",
        jobAssemblyName: "",
        jobDescription: "",
        jobParams: "",
        enable: true,
        jobBeginTime: null,
        jobEndTime: null,
    };
    dialogTitle.value = "添加任务";
    dialogVisible.value = true;
};

const handleSelectionChange = (rows) => {
    selectedRows.value = rows; // 将选中的行数据赋值给 selectedRows
};

// 打开编辑任务对话框
const openEditDialog = (job) => {
    currentJob.value = { ...job }; // 填充当前编辑任务的数据
    dialogTitle.value = "编辑任务";
    dialogVisible.value = true;
};

/** 保存任务（添加/编辑） */
const saveJob = async () => {
    try {
        if (currentJob.value.jobName === "") {
            alert("任务名称不能为空");
            return;
        }

        if (dialogTitle.value === "添加任务") {
            // 添加任务
            await AddJob(currentJob.value); // 假设你的后端API地址是 "/api/jobplans"
        } else {
            // 编辑任务
            await EditJob(currentJob.value);
        }
        getJobPlans(); // 刷新任务列表
    } catch (error) {
        console.error("保存任务失败", error);
    } finally {
        await initData();
        dialogVisible.value = false; // 关闭对话框
    }
};

// 立刻执行
const handleExecute = async () => {
    if (selectedRows.value.length !== 1) {
        // 如果没有选中一条任务，提示错误
        alert("请选择一条任务来执行");
        return;
    }
    const taskId = selectedRows.value[0].id; // 假设任务的唯一标识是 id
    await ExecuteJob(taskId);
};

//启动任务
const handleStart = async () => {
    if (selectedRows.value.length !== 1) {
        // 如果没有选中一条任务，提示错误
        alert("请选择一条任务来执行");
        return;
    }
    const taskId = selectedRows.value[0].id; // 假设任务的唯一标识是 id
    await StartJob(taskId);
    await initData();
}

/**停止任务 */
const handleStop = async () => {
    if (selectedRows.value.length !== 1) {
        // 如果没有选中一条任务，提示错误
        alert("请选择一条任务来执行");
        return;
    }
    const taskId = selectedRows.value[0].id; // 假设任务的唯一标识是 id
    await StopJob(taskId);
    await initData();
}

// 删除任务
const handleBatchDelete = async (jobName) => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择一条任务来执行");
        return;
    }

    const taskIds = selectedRows.value.map((row) => row.id);
    await DeleteJobs(taskIds);
    await initData();
    ElMessage.success("操作成功!");
};

const initData = async () => {
    var result = await QueryJobPlans();
    if (result != false) {
        console.log(result);
        jobPlans.value = result;
    }
};

// 页面加载时获取任务列表
onMounted(async () => {
    await initData();
});
</script>

<style scoped>
.job-plan {
    padding-top: 20px;
}

.mb-4 {
    margin-bottom: 10px;
}

.clear {
    margin-left: 10px;
}
</style>
